<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="scenarioName">
        <el-input
            v-model="queryParams.scenarioName"
            placeholder="输入实验场景名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="版本号" prop="version">
        <el-input
            v-model="queryParams.version"
            placeholder="输入版本号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-input
            v-model="queryParams.category"
            placeholder="输入分类"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-input
            v-model="queryParams.tags"
            placeholder="输入标签"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status"v-if="form.scenarioId">
        <el-select
            v-model="queryParams.status"
            placeholder="选择状态"
            clearable
        >
          <el-option label="已发布" value="已发布" />
          <el-option label="草稿" value="草稿" />
          <el-option label="已归档" value="已归档" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['platform:scenarios:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['platform:scenarios:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['platform:scenarios:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['platform:scenarios:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scenariosList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="100" align="center" />
      <el-table-column label="实验场景ID" align="center" prop="scenarioId" width="100" />
      <el-table-column label="实验场景名称" align="center" prop="scenarioName" width="230" />
      <el-table-column label="版本号" align="center" prop="version" width="100" />
      <el-table-column label="分类" align="center" prop="category" width="120" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === '已发布' ? 'success' : scope.row.status === '草稿' ? 'warning' : 'info'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="260">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['platform:scenarios:edit']">修改</el-button>
          <el-button
              link
              :type="scope.row.status === '已发布' ? 'danger' : 'success'"
              :icon="scope.row.status === '已发布' ? 'Bottom' : 'Top'"
              @click="toggleStatus(scope.row)"
              v-hasPermi="['platform:scenarios:publish']"
          >
            {{ scope.row.status === '已发布' ? '下架' : '发布' }}
          </el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['platform:scenarios:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改实验场景库对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="scenariosRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="场景名称" prop="scenarioName">
          <el-input v-model="form.scenarioName" placeholder="请输入场景名称" />
        </el-form-item>
        <el-form-item label="场景描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入场景描述" rows="3" />
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input v-model="form.version" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="实验文件" prop="filePath">
          <el-upload
              class="upload-demo"
              :limit="1"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              :file-list="fileList"
              :http-request="customUpload"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传.zip格式的实验场景文件
              </div>
            </template>
          </el-upload>
          <el-input v-model="form.filePath" placeholder="文件路径" style="margin-top: 10px;" readonly />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="form.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="form.tags" placeholder="请输入标签，多个标签用逗号分隔" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="草稿" value="草稿" />
            <el-option label="已发布" value="已发布" />
            <el-option label="已归档" value="已归档" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Scenarios">
import {
  listScenarios,
  getScenarios,
  delScenarios,
  addScenarios,
  updateScenarios,
  changeStatus,
  uploadScenarioFile
} from "@/api/platform/scenarios"

const { proxy } = getCurrentInstance()

const scenariosList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const fileList = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    scenarioName: null,
    description: null,
    version: null,
    filePath: null,
    category: null,
    tags: null,
    status: null
  },
  rules: {
    scenarioName: [
      { required: true, message: "实验场景名称不能为空", trigger: "blur" }
    ],
    filePath: [
      { required: true, message: "请上传实验场景文件", trigger: "blur" }
    ],
    status: [
      { required: true, message: "请选择发布状态", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

function customUpload(file) {
  return uploadScenarioFile(file.file).then(response => {
    form.value.filePath = response.data.filePath
    return response
  })
}

/** 查询实验场景库列表 */
function getList() {
  loading.value = true
  listScenarios(queryParams.value).then(response => {
    scenariosList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    scenarioId: null,
    scenarioName: null,
    description: null,
    version: null,
    filePath: null,
    category: null,
    tags: null,
    createTime: null,
    status: "草稿"
  }
  fileList.value = []
  proxy.resetForm("scenariosRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.scenarioId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加实验场景"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _scenarioId = row.scenarioId || ids.value
  getScenarios(_scenarioId).then(response => {
    form.value = response.data
    if (form.value.filePath) {
      fileList.value = [{ name: form.value.filePath.split('/').pop(), url: form.value.filePath }]
    }
    open.value = true
    title.value = "修改实验场景"
  })
}

/** 上传成功回调 */
function handleUploadSuccess(response, file) {
  form.value.filePath = response.data.filePath
}

/** 上传前校验 */
function beforeUpload(file) {
  const isZip = file.type === 'application/zip' || file.name.endsWith('.zip')
  if (!isZip) {
    proxy.$modal.msgError('只能上传.zip格式的文件!')
    return false
  }
  return true
}

/** 切换发布状态 */
function toggleStatus(row) {
  const newStatus = row.status === '已发布' ? '已归档' : '已发布'
  proxy.$modal.confirm(`确认要${newStatus === '已发布' ? '发布' : '下架'}实验场景"${row.scenarioName}"吗?`).then(() => {
    return changeStatus(row.scenarioId, newStatus)
  }).then(() => {
    proxy.$modal.msgSuccess(`${newStatus === '已发布' ? '发布' : '下架'}成功`)
    getList()
  }).catch(() => {})
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["scenariosRef"].validate(valid => {
    if (valid) {
      if (form.value.scenarioId != null) {
        updateScenarios(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addScenarios(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList().then(() => {
            reset() // 确保列表刷新后再重置表单
          })
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _scenarioIds = row.scenarioId || ids.value
  proxy.$modal.confirm('是否确认删除实验场景编号为"' + _scenarioIds + '"的数据项？').then(function() {
    return delScenarios(_scenarioIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('platform/scenarios/export', {
    ...queryParams.value
  }, `scenarios_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.upload-demo {
  margin-bottom: 10px;
}
</style>